<template>
  <a-tree-select
    style="width: 100%"
    allowClear
    v-model="stateValue"
    treeNodeFilterProp="title"
    :treeData="treeListData"
    :treeCheckable="multiple"
    :multiple="multiple"
    :placeholder="placeholder"
    :disabled="disabled"
    @change="onChange"
  />
</template>

<script>
  import { mapActions, mapState } from 'vuex'

  export default {
    name: 'SelectUser',
    props: {
      multiple: {
        type: Boolean,
        default: false,
      },
      value: {
        type: [Number, Array],
        default: undefined,
      },
      placeholder: {
        type: String,
        default: '请选择用户',
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      isUser: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        stateValue: this.value,
        treeListData: [],
      }
    },
    watch: {
      value(val) {
        this.stateValue = val
      },
    },
    async created() {
      if (!this.isUser) {
        this.treeData.length === 0 && this.onPage({ currentPage: 1, pageSize: 99999 })
        this.treeListData = this.treeData
      } else {
        await this.onRoleUserList()
        this.treeListData = this.roleUserListData
      }
    },
    mounted() {},
    computed: {
      ...mapState({
        loading: state => state.SysUser.loading,
        treeData: state => {
          return (
            (state.SysUser.pageData &&
              state.SysUser.pageData.records &&
              state.SysUser.pageData.records.map(item => {
                return {
                  title: item.name,
                  value: item.userId,
                  key: item.userId,
                }
              })) ||
            []
          )
        },
        roleUserListData: state => {
          return (
            state.SysUser.roleUserListData.map(item => {
              return {
                title: item.name,
                value: item.userId,
                key: item.userId,
              }
            }) || []
          )
        },
      }),
    },
    methods: {
      ...mapActions({
        onPage: 'SysUser/onPage',
        onRoleUserList: 'SysUser/onRoleUserList',
      }),
      onChange(value) {
        this.$emit('change', value)
        this.$emit('input', value)
      },
    },
  }
</script>

<style scoped lang="less"></style>
